import datetime

from webapp.extensions import AppException
from webapp.models import VScore, db, Session, VStu, VCourse, ScoreTable, Room, Plan


class ScoreService:
    @staticmethod
    def query_all(page=0, size=9999, **kwargs) -> list:
        create_times = kwargs.get('createTime')
        cname = kwargs.get('cname')
        courseId = kwargs.get('courseId')
        stuId = kwargs.get('stuId')
        sessionId = kwargs.get('sessionId')
        query = []
        if courseId:
            query.append(VScore.courseId==courseId)
        if sessionId:
            query.append(VScore.sessionId == sessionId)
        if stuId:
            query.append(VScore.stuId == stuId)
        if cname:
            query.append((VScore.cname.like(f'%{cname}%')))
        if create_times and len(create_times) >= 2:
            query.append((VScore.create_time.between(create_times[0], create_times[1])))
        result = VScore.query.filter(*query).paginate(int(page) + 1, per_page=int(size),
                                                      error_out=False)
        return result

    @staticmethod
    def find_by_id(id):
        scoretable = db.session.query(ScoreTable).filter(ScoreTable.id == id).one_or_none()
        if scoretable is None:
            raise AppException(f'您所操作的对象已不存在!')
        return scoretable

    @staticmethod
    def query_all_options():
        choiceOpts = {
            'courseIds': [],
            'stuIds': [],
            'sessionIds': [],
        }
        # 获取系统中的课程
        courses = VCourse.query.all()
        for course in courses:
            keyv = {
                'label': '{}_classId:{}'.format(course.cname, course.teachclass),
                'value': course.id
            }
            choiceOpts.get("courseIds").append(keyv)
        # 获取系统中的学生
        students = VStu.query.all()
        for stu in students:
            keyv = {
                'label': stu.nick_name,
                'value': stu.user_id
            }
            choiceOpts.get("stuIds").append(keyv)
        # 获取学期
        sessionIds = Session.query.order_by(Session.create_time).all()
        for sessionId in sessionIds:
            keyv = {
                'label': sessionId.session,
                'value': sessionId.id
            }
            choiceOpts.get("sessionIds").append(keyv)

        return choiceOpts

    @staticmethod
    def create(curr_score: ScoreTable):
        scoretable = ScoreTable.query.filter(ScoreTable.id == curr_score.id).one_or_none()
        if scoretable:
            raise AppException(f'{curr_score.id}已存在!')
        curr_score.create_time = datetime.datetime.now()
        ## 通过课程id 查询资源的相关信息
        courseInfo: VCourse = VCourse.query.filter(VCourse.id == curr_score.courseId).one_or_none()
        ## 通过课程id 查询教学类型
        plan: Plan = Plan.query.filter(Plan.id == courseInfo.plan).one_or_none()
        coursetable = ScoreTable(
            uId=curr_score.uId,
            sessionId=curr_score.sessionId,
            courseId=curr_score.courseId,
            resourceId=courseInfo.resource,
            teachtype=plan.teachtype,
            score=curr_score.score
        )
        db.session.add(coursetable)
        db.session.commit()

    @staticmethod
    def delete(score_set):
        if score_set:
            for couse in score_set:
                db.session.delete(couse)
            db.session.commit()

    @staticmethod
    def update(curr_score: ScoreTable):
        scoretable = ScoreTable.query.filter(ScoreTable.id == curr_score.id).one_or_none()

        ## 通过课程id 查询资源的相关信息
        courseInfo: VCourse = VCourse.query.filter(VCourse.id == curr_score.courseId).one_or_none()
        if courseInfo is None:
            raise AppException(f'绑定的课程不存在!')
        ## 通过课程id 查询教学类型
        plan: Plan = Plan.query.filter(Plan.id == courseInfo.plan).one_or_none()

        if scoretable is None:
            raise AppException(f'{curr_score.id}不存在!')
        scoretable.uId = curr_score.uId
        scoretable.sessionId = curr_score.sessionId
        scoretable.courseId = curr_score.courseId
        scoretable.resourceId = courseInfo.resource
        scoretable.teachtype = plan.teachtype
        scoretable.score = curr_score.score
        scoretable.update_time = datetime.datetime.now()
        scoretable.update_by = curr_score.update_by
        db.session.commit()

    @staticmethod
    def find_person_score_by_id(id):
        vscore = db.session.query(VScore).filter(VScore.id == id).one_or_none()
        if vscore is None:
            raise AppException(f'您所操作的对象已不存在!')
        return vscore

    @staticmethod
    def query_uId_SessionId(page=0, size=9999, **kwargs) -> list:
        uId = kwargs.get('uId')
        sessionId = kwargs.get('sessionId')
        query = []
        if uId:
            query.append(VScore.uId == uId)
        if sessionId:
            query.append(VScore.sessionId == sessionId)
        result = VScore.query.filter(*query).paginate(int(page) + 1, per_page=int(size),
                                                      error_out=False)
        return result

    @staticmethod
    def find_detail_score_by_id(id):
        result = VScore.query.filter(VScore.id==id).one_or_none()
        if result is None:
            raise AppException(f'该用户没有该课程的分数信息!')
        return result